import React, { useRef, useState } from "react";
import { useStore } from "@/store";
import { DeleteFilled } from "@ant-design/icons";
import { Button, message, Modal } from "antd";
import Editor from "react-simple-code-editor";
import { highlight, languages } from "prismjs";
import "prismjs/components/prism-clike.min";
import "prismjs/components/prism-javascript.min";
import "prismjs/themes/prism.css";

const SlideList = () => {
  const {
    sildeBgType,
    sildeBgVal,
    sildeBgVal2,
    slideList,
    currentSlideIndex,
    setCurrentPresentation,
    addSlide,
    deleteSlide,
  } = useStore();
  // 单个幻灯片
  const slideListItem = slideList?.[currentSlideIndex - 1] || [];

  const handleDeleteSlide = async (indexs) => {
    if (slideList.length < 2) {
      message.error("至少保留一个幻灯片");
      return;
    }
    try {
      Modal.confirm({
        title: "提示",
        content: (
          <>
            <div>确认是否要删除该幻灯片？</div>
          </>
        ),
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          const newSlideList = [...slideList];
          newSlideList.splice(indexs, 1);
          // 删除完重新排序
          newSlideList.forEach((item, index) => {
            item.sortId = index + 1;
          });
          deleteSlide(newSlideList);
        },
        onCancel: () => {},
      });
    } catch (error) {
      message.error("删除失败");
    }
  };

  // 判断什么语言;python、c、javascript、java
  const detectLanguage = (code) => {
    // Simple language detection based on common patterns
    const pythonPatterns = [
      /^#!/,
      /\bdef\b/,
      /\bprint\(/,
      /\bimport\b.*\n/,
      /:\s*$/m,
    ];

    const cPatterns = [
      /#include/,
      /int\s+main\s*\(/,
      /printf\s*\(/,
      /scanf\s*\(/,
      /void\s+\w+\s*\(/,
    ];

    const jsPatterns = [
      /const\s+/,
      /let\s+/,
      /function\s+/,
      /=>/,
      /console\.log/,
    ];

    const javaPatterns = [
      /public\s+class\s+\w+/,
      /public\s+static\s+void\s+main\s*\(/,
      /System\.out\.println/,
      /System\.in\.read/,
      /new\s+\w+\s*\(/,
    ];

    let pythonScore = 0;
    let cScore = 0;
    let jsScore = 0;
    let javaScore = 0;

    javaPatterns.forEach((pattern) => {
      if (pattern.test(code)) javaScore++;
    });

    pythonPatterns.forEach((pattern) => {
      if (pattern.test(code)) pythonScore++;
    });

    cPatterns.forEach((pattern) => {
      if (pattern.test(code)) cScore++;
    });

    jsPatterns.forEach((pattern) => {
      if (pattern.test(code)) jsScore++;
    });

    if (javaScore > cScore && javaScore > jsScore && javaScore > pythonScore)
      return "Java";
    if (pythonScore > cScore && pythonScore > jsScore) return "Python";
    if (cScore > pythonScore && cScore > jsScore) return "C";
    return "JavaScript";
  };

  return (
    <div
      style={{
        position: "relative",
        height: "calc(100vh - 140px)",
        paddingBottom: 10,
        overflowX: "hidden",
        overflowY: "auto",
      }}
    >
      {slideList?.map((items, indexs) => {
        return (
          <>
            <div
              key={items.id}
              style={{
                width: 224,
                height: 114,
                marginBottom: 20,
                marginLeft: 20,
                marginRight: 10,
                border: "1px solid #e8e8e8",
                position: "relative",
                boxShadow:
                  items.sortId === currentSlideIndex
                    ? `0 1px 2px 0 rgba(0, 0, 0, 0.13), 0 1px 6px -1px rgba(0, 0, 0, 0.12),0 2px 4px 0 rgba(0, 0, 0, 0.12)`
                    : "0 0px 0px 0 rgba(0, 0, 0, 0)",
                background:
                  items?.sildeBgType == "gradient"
                    ? `linear-gradient(to bottom right,${items?.sildeBgVal},${items?.sildeBgVal2})`
                    : items?.sildeBgType == "img"
                    ? `url(${items?.sildeBgVal}) 0% 0% / cover no-repeat`
                    : items?.sildeBgVal || "#fff",
                backgroundSize: "cover", // 设置背景图片大小
                backgroundRepeat: "no-repeat", // 设置背景图片不重复
              }}
              onClick={() => {
                setCurrentPresentation(items.sortId);
              }}
            >
              <div
                style={{
                  position: "absolute",
                  top: 0,
                  left: 0,
                  width: 220,
                  height: 110,
                  background: "red",
                  opacity: 0,
                  zIndex: 2,
                }}
              />
              <div
                style={{
                  position: "absolute",
                  top: 0,
                  right: 0,
                  zIndex: 10,
                  display: "block",
                  fontSize: 16,
                  cursor: "pointer",
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                  handleDeleteSlide(indexs);
                }}
              >
                <DeleteFilled />
              </div>
              <div
                style={{
                  display: "flex",
                  flexDirection: "row",
                  flexWrap: "wrap",
                  justifyContent: "space-between",
                  width: 1100,
                  height: 550,
                  margin: "auto",
                  padding: 16,
                  paddingRight: 8,
                  overflow: "hidden",
                  transform: "scale(0.2)",
                  marginTop: -220,
                  marginLeft: -440,
                }}
              >
                {items?.elements?.map((item) => {
                  // 文本
                  if (item.type === "Text") {
                    return (
                      <div
                        key={item?.id}
                        style={{
                          marginBottom: 16,
                          cursor: "pointer",
                          border: "1px solid #e8e8e8",
                          color: item?.fontColor || "#000000",
                          fontSize: `${item?.fontSize || 18}em`,
                          fontWeight: item?.fontWight || 800,
                          overflow: "hidden",
                          fontFamily: item?.fontFamily || "auto",
                          position: "absolute",
                          width: `${item?.blockWidth || 100}%`,
                          height: `${item?.blockHeight || 50}%`,
                          left: `${item?.xAxis || 0}%`,
                          top: `${item?.yAxis || 0}%`,
                        }}
                      >
                        {item?.content}
                      </div>
                    );
                  }
                  // 图片
                  if (item.type === "Image") {
                    // asdas
                    return (
                      <div
                        style={{
                          marginBottom: 16,
                          cursor: "pointer",
                          position: "absolute",
                          width: `${item?.blockWidth || 100}%`,
                          height: `${item?.blockHeight || 50}%`,
                          left: `${item?.xAxis || 0}%`,
                          top: `${item?.yAxis || 0}%`,
                        }}
                        key={item.id}
                      >
                        <img
                          style={{
                            width: "100%",
                            height: "100%",
                          }}
                          src={item?.imageUrl}
                          alt={item?.describe}
                        />
                      </div>
                    );
                  }
                  // 视频
                  if (item.type === "Video") {
                    return (
                      <div
                        key={currentSlideIndex}
                        style={{
                          marginBottom: 16,
                          cursor: "pointer",
                          position: "absolute",
                          width: `${item?.blockWidth || 100}%`,
                          height: `${item?.blockHeight || 50}%`,
                          left: `${item?.xAxis || 0}%`,
                          top: `${item?.yAxis || 0}%`,
                        }}
                      >
                        <video
                          style={{
                            border: "1px solid #e8e8e8",
                            verticalAlign: "middle",
                            objectFit: "fill",
                          }}
                          width="100%"
                          height="100%"
                          controls
                          // 阻止默认的双击全屏行为
                          controlsList="nofullscreen"
                        >
                          <source
                            src={item?.videoUrl || 250}
                            type="video/mp4"
                          />
                          Your browser does not support the video tag.
                        </video>
                      </div>
                    );
                  }
                  // 代码
                  if (item.type === "Code") {
                    return (
                      <div
                        style={{
                          marginBottom: 16,
                          cursor: "pointer",
                          position: "absolute",
                          width: `${item?.blockWidth || 100}%`,
                          height: `${item?.blockHeight || 50}%`,
                          left: `${item?.xAxis || 0}%`,
                          top: `${item?.yAxis || 0}%`,
                        }}
                        key={item.id}
                      >
                        <div
                          style={{
                            width: "500px",
                            height: 250,
                            overflow: "hidden",
                            border: "1px solid #e8e8e8",
                            backgroundColor:
                              detectLanguage(item?.content) === "Python"
                                ? "#eef6ff"
                                : detectLanguage(item?.content) === "JavaScript"
                                ? "#fefce8"
                                : "#fbf5ff",
                          }}
                        >
                          <div
                            style={{
                              width: "100%",
                              height: 40,
                              padding: "0 16px",
                              lineHeight: "38px",
                              borderBottom: "1px solid #e8e8e8",
                            }}
                          >
                            {detectLanguage(item?.content)}
                          </div>
                          <Editor
                            value={item?.content}
                            highlight={(code) =>
                              highlight(code, languages.js, "javascript")
                            }
                            padding={4}
                            style={{
                              display: "block",
                              width: "100%",
                              height: "100%",
                              overflow: "hidden",
                              border: "0px",
                              fontFamily: '"Fira code", "Fira Mono", monospace',
                              fontSize: item?.fontSize * 16 || 12,
                            }}
                            readOnly
                          />
                        </div>
                      </div>
                    );
                  }
                  return null;
                })}
              </div>
            </div>
          </>
        );
      })}
      <div
        style={{
          position: "fixed",
          bottom: 10,
          left: 10,
          // background: 'red',
          width: 250,
          height: 36,
          textAlign: "center",
        }}
      >
        <Button
          type="text"
          onClick={() => {
            addSlide();
          }}
        >
          +新增幻灯片
        </Button>
      </div>
    </div>
  );
};

export default SlideList;
